<template>
  <div class="h-p100 w-p100">
    <div class="box box-ver w-p100 h-p100">
      <div @click="$router.replace('/')"  class="header box box-ac">
        <div class="icon icon-back"></div>
        <div class="box-f1 tx-c">登录</div>
      </div>
      <div class="box box-ac box-ver box-f1 of-y-s">
        <input v-model="user.email" class="email" placeholder="请输入邮箱"  type="text">
        <input v-model="user.password" class="password" placeholder="请输入密码" type="password">
        <div @click="login" class="submit">登录</div>
        <div @click="$router.replace('/register')" class="signUp submit">注册</div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'login',
  data () {
    return {
      user: {
        email: '',
        password: ''
      }
    }
  },
  computed: {
    ...mapState(['userInfo'])
  },
  mounted () {
    let query = this.$route.query
    if (this.userInfo.email) {
      this.user.email = this.userInfo.email
      this.user.password = this.userInfo.password
    }
    if (query.autoLogin === 1) this.login()
  },
  methods: {
    login () {
      let { email, password } = this.user
      if (!/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email)) {
        this.$tools.openToast({
          msg: '邮箱格式错误',
          duration: 1500
        })
        return
      }
      if (!password) {
        this.$tools.openToast({
          msg: '请输入密码',
          duration: 1500
        })
        return
      }
      this.$http({
        method: 'post',
        url: `${this.$config.apiBase}/api/v0/user/login`,
        data: {
          email,
          password
        }
      }).then(res => {
        if (res.status !== 1) return
        let redirect = this.$route.query.redirect || '/'
        this.$store.commit('userInfo', res.data.user)
        this.$router.replace(redirect)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../assets/css/config.scss';
input, .submit{
  display:block;
  width:5rem;
  height:.75rem;
  border-radius: .75rem;
  font-size:.36rem;
  text-align: center;
  margin-bottom:.3rem;
  background-color:#FFF;
  border:1px solid $themeColor;
  outline: none;
  color:#666;
  &.email{
    margin-top:3.6rem;
  }
  &.submit{
    color:#FFF;
    background-color:$themeColor;
    line-height:.75rem;
    margin-top:.5rem;
    &.signUp{
      color:$themeColor;
      background-color:#FFF;
    }
  }
}
</style>
